import 'package:flutter/material.dart';

typedef FinishListener = Function(Widget widget);

class LikeAnimalIcon extends StatefulWidget {
  FinishListener mFinishListener;

  LikeAnimalIcon({required this.mFinishListener});

  @override
  _LikeAnimalIconState createState() {
    return _LikeAnimalIconState();
  }
}

class _LikeAnimalIconState extends State<LikeAnimalIcon>
    with TickerProviderStateMixin {
  late AnimationController mAnimationController;

  late Animation<double> opacityAnimation;

  late Animation<double> scaleAnimation;

  late Animation<double> fadeOutAnimation;

  @override
  void initState() {
    super.initState();
    mAnimationController = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 5),
    );
    mAnimationController.addStatusListener((state) {
      if (state.isCompleted) {
        widget.mFinishListener(widget);
      }
    });
    mAnimationController.addListener(() => setState(() {}));

    // 透明度动画 (0-0.3时间段)
    opacityAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(
        parent: mAnimationController,
        curve: const Interval(0.0, 1, curve: Curves.easeIn),
      ),
    );

    /*  // 缩放动画 (0.3-0.7时间段)
    scaleAnimation = Tween<double>(begin: 1.0, end: 1.5).animate(
      CurvedAnimation(
        parent: mAnimationController,
        curve: const Interval(0.3, 0.7, curve: Curves.elasticOut),
      ),
    );

    // 消失动画 (0.7-1.0时间段)
    fadeOutAnimation = Tween<double>(begin: 1.0, end: 0.0).animate(
      CurvedAnimation(
        parent: mAnimationController,
        curve: const Interval(0.7, 1.0, curve: Curves.easeOut),
      ),
    );*/
    mAnimationController.forward();
  }

  @override
  void dispose() {
    super.dispose();
    mAnimationController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return _bulid();
  }

  Widget _bulid() {
    return Opacity(
      opacity: opacity,
      child: Icon(Icons.favorite, color: Colors.blue, size: iconSize),
    );
  }

  double get curValue => mAnimationController.value;

  double get opacity {
    if (curValue < 0.3) {
      return 1 / 0.3 * curValue;
    } else if (curValue > 0.7) {
      return 1 / 0.3 * (1 - curValue);
    }

    return 1;
  }

  double? get iconSize {
    if (curValue < 0.3) {
      return 100;
    } else if (curValue > 0.7) {
      return 150;
    } else {
      print("iconSize ${curValue} ${50 / 0.4 * (curValue - 0.3) + 100}");
      return 50 / 0.4 * (curValue - 0.3) + 100;
    }
  }
}
